import { useNavigatePage } from '@/hooks/navigateTo'
import useToastMsg from '@/hooks/sysMsg'
import { getPlatformInfo } from '@/utils/platform'
const toastMsg = useToastMsg()
import { BaseResultType } from '#/request'
import useDealResult from '@/hooks/dealResult'
import uniRequest from '@/request'
import { confirmOrder } from '@/api/index'
const { dealResult, checkResult } = useDealResult()
const navigatePage = useNavigatePage()
export const getPayParam = async (param: any): Promise<BaseResultType<any> | null> => {
  const [result, err] = await uniRequest.post('/wxapi/order/pay', param)
  return Promise.resolve(dealResult(err, result))
}
export const wxPayFun = async (param: any) => {
  // new Promise(async (resolve, reject) => {
  if (getPlatformInfo().platform === 'WEIXIN') {
    const result = await getPayParam(param)
    if (result) {
      try {
        toastMsg.showLoading('支付中...')
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: result.data.payment.timeStamp.toString(),
          nonceStr: result.data.payment.nonceStr,
          package: result.data.payment.package,
          signType: 'MD5',
          paySign: result.data.payment.paySign,
          orderInfo: result.data.payment.orderInfo,
          success: async (res) => {
            toastMsg.successMsg('支付成功')
            // resolve(true)
            const result = await confirmOrder(param.userStorageId)
            if (result) {
              if (result.data.code == 0) {
                toastMsg.showToast('寄存成功')
                navigatePage.redirectTo(`/pages/baoguo/index`)
              }
            }
          },
          fail: (err) => {
            toastMsg.showToast('支付失败')
          },
          complete: () => {
            toastMsg.hideLoading()
          },
        })
      } catch (err: any) {
        if (err.errMsg && err.errMsg.includes('cancel')) {
          toastMsg.showToast('已取消支付')
        } else {
          toastMsg.errorMsg(`支付失败: ${err.errMsg || '未知错误'}`)
        }
        // resolve(false)
      }
    }
    // resolve(false)
  } else {
    toastMsg.errorMsg('请在微信小程序中使用微信支付')
    // resolve(false)
  }
}
// })
// const paySubmitFun = async () => {
//   const result = await confirmOrder(roomInfo.value.userStorageId)
//   if (result) {
//     if (result.data.code == 0) {
//       toastMsg.showToast('寄存成功')
//       navigatePage.redirectTo(`/pages/baoguo/index`)
//       // navigatePage.redirectTo(`/pages/index/index`)
//       // navigatePage.redirectTo(`/pages/confirmRoom/payDetail?userStorageId=` + roomInfo.value.userStorageId)
//     }
//   }
// }
